from django.http import JsonResponse
import json,requests,datetime
import base64,rsa,time
from Crypto.PublicKey import RSA
from rest_framework.decorators import api_view
from buildapi.models import BuildingInfo
from guestapi.models import GuestInfo
# Create your views here.


@api_view(['POST'])
def dispatcher(request):  

    # try:
    if request.user.is_authenticated:   # 验证Token是否正确
        if request.user.is_active:
            if request.method == 'GET':
                request.params = request.GET

            # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
            elif request.method in ['POST','PUT','DELETE']:
                # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
                request.params = json.loads(request.body)


            # 根据不同的action分派给不同的函数进行处理
            action = request.params['action']
            if action == 'list':
                return ikuai_list(request)
            elif action == 'add':
                return ikuai_add(request)
            elif action == 're':
                return ikuai_re(request)
            elif action == 'del':
                return ikuai_del(request)
            elif action == 'enabled':
                return ikuai_enabled(request)
            elif action == 'user':
                return ikuai_user(request)



            else:
                return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})
    else:
        return JsonResponse({'ret': 2, "msg": "token验证失败"})


def ikuai_list(request):
    data = json.loads(request.body)
    building_id = data['building_id']
    index = BuildingInfo.objects.filter(building_id=building_id).values()
    building_about_ikuai = list(index)[0]['building_about_ikuai']
    token = ikuai_token()
    from_data = {
    "param" : {
        "TYPE" : "data"
    }
    }

    from_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close', 'IK-Access-Token': '{}'.format(token)}

    response = requests.post('https://open.ikuai8.com/api/v3/open/1/{}'.format(building_about_ikuai), data=json.dumps(from_data), headers=from_header)
    res = response.json()
    return JsonResponse(res)


def ikuai_user(request):
    data = json.loads(request.body)
    building_id = data['building_id']
    username = data['username']

    index = BuildingInfo.objects.filter(building_id=building_id).values()
    building_about_ikuai = list(index)[0]['building_about_ikuai']
    token = ikuai_token()
    from_data = {
    "param" : {
        "username" : username
    }
    }

    from_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close', 'IK-Access-Token': '{}'.format(token)}

    response = requests.post('https://open.ikuai8.com/api/v3/open/11/{}'.format(building_about_ikuai), data=json.dumps(from_data), headers=from_header)
    res = response.json()
    return JsonResponse(res)


def ikuai_add(request):
    data = json.loads(request.body)
    guest_id = data['guest_id']
    building_id = data['building_id']
    share = data['share']
    download = data['download']
    username = data['username']
    password = data['password']

    re = GuestInfo.objects.get(guest_id=guest_id)
    if re.guest_network_id != None:
        return JsonResponse({'ret':1,'msg':'该用户已绑定上网账号'})
    index = BuildingInfo.objects.filter(building_id=building_id).values()
    building_about_ikuai = list(index)[0]['building_about_ikuai']
    token = ikuai_token()
    from_data = {
    "param" : {
        "share" : share,
        "download" : download,
        "auto_mac" : 0,
        "cardid": str(guest_id),
        "name": re.guest_name,
        "bind_vlanid" : "0",
        "username" : username,
        "ppptype" : "any",
        "upload" : 0,
        "packages" : 0,
        "passwd" : password,
        "create_time" : int(time.time()),
        "enabled" : "yes",
        "start_time" : int(time.time()),
        "bind_ifname" : "any",
        "auto_vlanid" : 1,
        "last_conntime" : 0,
        "expires": 0
    }
    }

    from_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close', 'IK-Access-Token': '{}'.format(token)}

    response = requests.post('https://open.ikuai8.com/api/v3/open/5/{}'.format(building_about_ikuai), data=json.dumps(from_data), headers=from_header)
    res = response.json()
    if 'Extra' not in res:
        return JsonResponse(res)
    elif res['Extra']['RowId'] == 0:
        return JsonResponse(res)
    else:
        guest_network_id = res['Extra']['RowId']

    now_time = datetime.datetime.strptime(datetime.datetime.now().strftime(f'%Y-%m-%d'),f'%Y-%m-%d')

    re.guest_network_id = guest_network_id
    re.guest_network_name = username
    re.guest_network_date = now_time
    re.guest_network_day = 0
    re.guest_network_last = 0
    re.guest_network_price = 0
    re.guest_network_price_type = 0
    re.save()
    
    return JsonResponse(res)

def ikuai_re(request):
    data = json.loads(request.body)
    share = data['share']
    download = data['download']
    username = data['username']
    password = data['password']
    guest_id = data['guest_id']
    building_id = data['building_id']

    re = GuestInfo.objects.get(guest_id=guest_id)
    index = BuildingInfo.objects.filter(building_id=building_id).values()
    building_about_ikuai = list(index)[0]['building_about_ikuai']
    token = ikuai_token()
    from_data = {
    "param" : {
        "share" : share,
        "download" : download,
        "auto_mac" : 0,
        "cardid": str(guest_id),
        "name": re.guest_name,
        "bind_vlanid" : "0",
        "username" : username,
        "ppptype" : "any",
        "upload" : 0,
        "id" : re.guest_network_id,
        "packages" : 0,
        "passwd" : password,
        "create_time" : int(time.time()),
        "enabled" : "yes",
        "start_time" : int(time.time()),
        "bind_ifname" : "any",
        "auto_vlanid" : 1,
        "last_conntime" : 0,
        "expires": 0
    }
    }

    from_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close', 'IK-Access-Token': '{}'.format(token)}

    response = requests.post('https://open.ikuai8.com/api/v3/open/6/{}'.format(building_about_ikuai), data=json.dumps(from_data), headers=from_header)
    res = response.json()

    re.guest_network_name = username
    re.save()

    return JsonResponse(res)


def ikuai_del(request):
    data = json.loads(request.body)
    guest_id = data['guest_id']
    building_id = data['building_id']

    re = GuestInfo.objects.get(guest_id=guest_id)
    index = BuildingInfo.objects.filter(building_id=building_id).values()
    building_about_ikuai = list(index)[0]['building_about_ikuai']
    token = ikuai_token()
    from_data = {
    "param" : {
        "id" : re.guest_network_id
    }
    }

    from_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close', 'IK-Access-Token': '{}'.format(token)}

    response = requests.post('https://open.ikuai8.com/api/v3/open/8/{}'.format(building_about_ikuai), data=json.dumps(from_data), headers=from_header)
    res = response.json()

    re.guest_network_id = None
    re.guest_network_name = None
    re.guest_network_date = None
    re.guest_network_day = None
    re.guest_network_last = None
    re.guest_network_price = 0
    re.guest_network_price_type = 2
    re.save()

    return JsonResponse(res)


def ikuai_enabled(request):
    data = json.loads(request.body)
    guest_id = data['guest_id']
    building_id = data['building_id']
    status = data['status']
    
    re = GuestInfo.objects.get(guest_id=guest_id)
    index = BuildingInfo.objects.filter(building_id=building_id).values()
    building_about_ikuai = list(index)[0]['building_about_ikuai']
    token = ikuai_token()
    from_data = {
    "param" : {
        "id" : re.guest_network_id,
        "status" : status
    }
    }

    from_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close', 'IK-Access-Token': '{}'.format(token)}

    response = requests.post('https://open.ikuai8.com/api/v3/open/7/{}'.format(building_about_ikuai), data=json.dumps(from_data), headers=from_header)
    res = response.json()
    return JsonResponse(res)


@api_view(['POST'])
def my_enabled(request):
    data = json.loads(request.body)
    building_id = data['building_id']
    uid = data['uid']
    status = data['status']
    index = BuildingInfo.objects.filter(building_id=building_id).values()
    building_about_ikuai = list(index)[0]['building_about_ikuai']
    token = ikuai_token()
    from_data = {
    "param" : {
        "id" : uid,
        "status" : status
    }
    }

    from_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close', 'IK-Access-Token': '{}'.format(token)}

    response = requests.post('https://open.ikuai8.com/api/v3/open/7/{}'.format(building_about_ikuai), data=json.dumps(from_data), headers=from_header)
    res = response.json()
    return JsonResponse(res)


def ikuai_token():
    # 获取token
    # 生成秘钥对象
    public = '''-----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiwGEjf8tUjh2sr43YncN+yM/s
    6GeHgNiTxQ7F5IOO4Fv7hwTKpi0oo05mIRTOK4Nk5fYNqv/SZZO6OiH6EpVfb7wK
    U8kVYYJ5JzI/5o3iJnR9ki01i1ztW0Y/oHa46zsU/DQSZ70UWm+Cw3cehhFlFQtG
    roJsskNxU+LY61q3bQIDAQAB
    -----END PUBLIC KEY-----'''
    key = RSA.import_key(public)

    # 加密
    msg = str(int(time.time())).encode()
    password = rsa.encrypt(msg,key)
    # 转换base64
    sign = base64.b64encode(password).decode()

    #构建data
    token_data = {
    "client_type" : "OPEN_PARTNER",
    "client_id" : "ikof1600985829ebb44",
    "request_time" : int(msg.decode()),
    "options" : {
        "token_lifetime" : 7200
    },
    "sign" : sign
    }

    token_header = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close'}

    response = requests.post('https://open.ikuai8.com/api/v3/open/access_token', data=json.dumps(token_data), headers=token_header)
    res = response.json()

    token = res['access_token']
    return token